﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace t_205_verk_hopur_12.Models
{
    public class UserRepository : t_205_verk_hopur_12.Models.IUserRepository
    {
        public MittTVDataContext db = new MittTVDataContext();

        // To add a new user
        public void Add(User user)
        {
            db.Users.InsertOnSubmit(user);
        }
        
        // To get a specific user by username
        public User GetUserInfoByUsername(string name)
        {
            return db.Users.SingleOrDefault(u => u.Username == name);
        }

        //To get a specifity user by ID
        public User GetUserByID(int id)
        {
            return db.Users.SingleOrDefault(u => u.ID == id);
        }

        // To save the changes to database
        public void Save()
        {
            db.SubmitChanges();
        }

        // Get all channels that userID owns
        public IEnumerable<Channel> GetOwnedChannels(int userID)
        {
            var result = from ch in db.Channels
                         where ch.OwnerID == userID
                         select ch;
            return result;
        }

        // Get all channels that userID is subscribed to
        public IEnumerable<Channel> GetSubscribedChannels(int userID)
        {
            return (from c in db.Channels
                    join s in db.Subscriptions on c.ID equals s.ChannelID
                    where s.UserID == userID
                    select c);
        }

        // Get all channels that userID is an employee at
        public IEnumerable<Channel> GetEmployedAtChannels(int userID)
        {
            return (from c in db.Channels
                    join s in db.Permissions on c.ID equals s.ChannelID
                    where s.UserID == userID
                    select c);
        }
    }
}
